/* components */
import Chat from '@src/component/business/BizChatPanel/chat'
import { Loading } from 'element-ui';
import app from '@src/component/business/BizChatPanel/app'
/* enum */
import ComponentNameEnum from "@model/enum/ComponentNameEnum";
import StorageKeyEnum from '@model/enum/StorageKeyEnum';
/* vue */
import { defineComponent, ref } from "vue";
/* hooks */
import { useBaoGPTSetting, useSettingGPTRobotHome } from "@src/modules/setting/gpt/hooks";
/* model */
import { SettingGPTServiceTypeEnum } from '@gpt/model';
/* util */
import { isFalsy } from "@src/util/type";
import { uuid } from '@src/util/lang/string'
/* scss */
import "@src/modules/setting/gpt/views/chat/index.scss";
/* api */
import { getRobot, getRobotShare } from '@src/api/AIApi';
/* model */
import MsgModel from '@model/MsgModel';
/* util */
import { parse_with_default_value } from '@src/util/lang/object';
import { isNotUndefined, isNull } from 'pub-bbx-utils';
/* types */
import { SettingGPTServiceItem } from '@gpt/types';
import { AIChatRobotItemType } from '@src/component/business/BizChatPanel/chat/types';

export default defineComponent({
  name: ComponentNameEnum.SettingGPTChatView,
  components: {
    Chat,
    app
  },
  props: {
    
  },
  setup(props, { emit }) {
    
    const isShare = ref(true)
    
    const {
      loading,
      gptRobotAppList,
      onfetchGptRobotAppListHandler,
    } = useSettingGPTRobotHome(isShare)
    
    return {
      loading,
      gptRobotAppList,
      onfetchGptRobotAppListHandler,
    }
    
  },
  data() {
    return {
      isShare: true,
      userId: '',
      stream: undefined as any,
      loadingInstance: null as any,
      loading: false,
      currentApp: undefined as unknown as SettingGPTServiceItem | undefined,
      isShowAppService: false,
      isLoadFinish: false,
      isOpenShare: true,
      isRobotFail: false,
      isRobotAppFail: false,
      isRobotEnable: true,
      isRobotDelete: false,
      robotName: '',
    }
  },
  computed: {
    disabled(): boolean {
      return this.loading || this.isRobotFail || this.isRobotAppFail
    },
    query(): Record<string, any> {
      return this.$route.query || {}
    },
    robotId(): string {
      return this.query.robotId
    },
    tenantId(): string {
      return this.query.tenantId
    },
    isAICustomerService(): boolean {
      return this.query.isAICustomerService
    },
    isShowChat(): boolean {
      return isNotUndefined(this.stream)
    },
    notShowAppTypes(): string[] {
      return [
        SettingGPTServiceTypeEnum.Intelligent,
        SettingGPTServiceTypeEnum.BI
      ]
    },
    insideGptRobotAppList(): SettingGPTServiceItem[] {
      return this.gptRobotAppList
    },
    noPermissionText(): string {
      if (this.isRobotDelete) {
        return '机器人已被删除，无法使用。'
      }
      if (isFalsy(this.isRobotEnable)) {
        return '机器人已被禁用，请先开启再使用。'
      }
      return ''
    },
    isHaveAuth(): boolean {
      return this.isRobotEnable && isFalsy(this.isRobotDelete)
    },
    chatSystemMessage(): string {
      
      if (isFalsy(this.isAICustomerService)) {
        return ''
      }
      
      return `
        🌟 欢迎来到AI客户服务 🌟 </br>
        您好！我是“AI客户服务”，您的数字化客户专家。我擅长在多种行业领域提供智能客户服务解决方案。在客户服务领域拥有超过10年的行业经验，处理过超过50,000个客户服务案例，构建了一个包含各种解决方案的庞大知识库。</br>
        🚀 “AI客户服务 —— 智慧客户服务，服务不打烊！ 🚀 </br>
      `
      
    }
  },
  watch: {
    loading: {
      immediate: true,
      handler(loading) {
        if (loading) {
          this.loadingInstance = Loading.service({
            target: this.$el as HTMLElement,
            fullscreen: true,
            lock: true,
            text: '正在启用您的智能 AI 助手...'
          })
        } else {
          this.loadingInstance?.close()
        }
      }
    }
  },
  methods: {
    init() {
      // @ts-ignore
      this.$refs.ChatView.init()
    },
    initChat() {
      
    },
    getUserId() {
      
      const storageUserId = localStorage.getItem(StorageKeyEnum.ChatShareUserId)
      
      if (storageUserId) {
        return storageUserId
      }
      
      const userId = uuid()
      
      localStorage.setItem(StorageKeyEnum.ChatShareUserId, userId)
      
      return userId
    },
    getRobot() {
      
      this.loading = true
      
      const params = {
        id: this.robotId,
        tenantId: this.tenantId
      }
      
      return getRobotShare(params).then(result => {
        
        if (MsgModel.isFail(result)) {
          this.isRobotFail = true
          return 
        }
        
        const data = MsgModel.getData(result, {} as AIChatRobotItemType)
        const isRobotDeleted = isNull(data.id)
        
        if (isRobotDeleted) {
          this.isRobotDelete = true
          return
        }
         
        const setting = parse_with_default_value(data.setting, {} as Record<string, any>)
        const stream = Boolean(setting.stream)
        const isOpenShare = Boolean(setting.share)
        this.stream = stream
        this.isRobotEnable = Boolean(data.enable)
        this.isRobotDelete = Boolean(data.deleteTag)
        this.robotName = data.name
        
        document.title = this.robotName
        
      })
      .catch(error => {
        this.isOpenShare = false
        this.stream = false
        console.error(error)
      })
      .finally(() => {
        this.loading = false
      })
    },
    onAppTagClickHandler() {
      this.isShowAppService = true
    },
    onBackHandler() {
      this.isShowAppService = false
    },
    onCancelHandler() {
      this.onBackHandler()
    },
    onConfirmHandler(type: string) {
      
      this.onBackHandler()
      
      this.currentApp = this.gptRobotAppList.find(item => {
        return item.type == type
      })
      
      this.init()
      this.initChat()
      
    }
  },
  async created() {
    
    this.userId = this.getUserId()
    
    await this.getRobot()
    
    const robotAppResult = await this.onfetchGptRobotAppListHandler(this.robotId, this.tenantId)
    
    if (isFalsy(robotAppResult) || MsgModel.isFail(robotAppResult)) {
      this.isRobotAppFail = true
    }
    
    this.currentApp = this.gptRobotAppList.find(item => {
      return item.type == SettingGPTServiceTypeEnum.Common || item.type == SettingGPTServiceTypeEnum.Intelligent
    })
    
    this.isLoadFinish = true
    
  },
  render() {
    return (
      <permission auth={this.isHaveAuth} text={this.noPermissionText}>
        <div class={ComponentNameEnum.SettingGPTChatView}>
          
          {this.isLoadFinish && (
            <Chat
              v-show={!this.isShowAppService}
              ref="ChatView"
              disabled={this.disabled}
              currentApp={this.currentApp}
              isShare={this.isShare}
              robotId={this.robotId}
              tenantId={this.tenantId}
              userId={this.userId}
              stream={this.stream}
              chatSystemMessage={this.chatSystemMessage}
              onAppTag={this.onAppTagClickHandler}
            />
          )}
          
          <app
            ref="AppServiceView"
            v-show={this.isShowAppService}
            currentApp={this.currentApp}
            list={this.insideGptRobotAppList}
            onCancel={this.onCancelHandler}
            onConfirm={this.onConfirmHandler}
          />
          
        </div>
      </permission>
    )
  }
});